package cn.wit.summit.chwan.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.ResponseSratues;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.request.FollowGamesRequest;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.MessageDialog;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by pengsk on 2018/4/19.
 */

public class MYFollowGamsActivity extends MyActivity {
    @Bind(R.id.recommendTopWallet)
    RecommendTopWalletV2View topBarWallet;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadV2View topBarDownload;
    @Bind(R.id.recvcleView)
    RecyclerView recvcleView;
    @Bind(R.id.root_content_null_ll)
    FrameLayout root_content_null_ll;
    @Bind(R.id.retryText)
    TextView retryText;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.retryImg)
    ImageView retryImg;

    List<GameListBaseBean> games = new ArrayList<>();
    LayoutInflater inflater;
    Context context;
    private int pn = 1;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follow_games);
        ButterKnife.bind(this);
        setBarTitleTx("收藏");

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        context = this;
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        pn = 1;
        getfolowgames();
    }

    MYUpdateAdapter adapter = null;

    private void initView() {
        hideTitleBar();
        httptag = System.currentTimeMillis() + "";
        inflater = LayoutInflater.from(context);
        recvcleView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new MYUpdateAdapter();
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.item_driver_h));
        recvcleView.addItemDecoration(divider);
        recvcleView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getfolowgames();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getfolowgames();
            }
        });

        setTopBarDownload(topBarDownload, topBarWallet);
    }

    private void getfolowgames() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            FollowGamesRequest request = retrofitManager.followGamesRequest(AccountUtil.getInstance().getUid(), pn, AccountUtil.getInstance().getToken());
            api.getFollowGames(request).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
                        @Override
                        public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                            List<GameListBaseBean> data = model.getData_info();
                            if (data != null) {
                                if (pn == 1) {
                                    games.clear();
                                    refreshLayout.finishRefresh();
                                    refreshLayout.setNoMoreData(false);
                                    pn++;
                                } else {
                                    if (data.size() > 0) {
                                        refreshLayout.finishLoadMore();
                                        pn++;
                                    } else {
                                        refreshLayout.finishLoadMoreWithNoMoreData();
                                    }

                                }
                                games.addAll(data);
                            } else {
                                if (pn == 1) {
                                    refreshLayout.finishRefresh();
                                } else {
                                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                            adapter.notifyDataSetChanged();
                            if (games.size() == 0) {
                                root_content_null_ll.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                                retryImg.setImageResource(R.mipmap.ic_not_data);
                                retryText.setText("暂无相关数据");
                            } else {
                                root_content_null_ll.setVisibility(View.GONE);
                                refreshLayout.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            ToastUtils.getInstance(context).showToastSystem(msg);
                            if (games.size() == 0) {
                                topLayout.setVisibility(View.VISIBLE);
                                topLayout.setVisibility(View.VISIBLE);
                                showFailedLoding(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        topLayout.setVisibility(View.GONE);
                                        hideFailedLoding();
                                        getfolowgames();
                                    }
                                });
                            }
                            if (code == -3) {
                                root_content_null_ll.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                                retryImg.setImageResource(R.mipmap.ic_not_net);
                                retryText.setText("网络异常，点击屏幕重新加载");
                            }
                        }
                    });
        } else {
            if (games.size() == 0) {
                root_content_null_ll.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
                retryImg.setImageResource(R.mipmap.ic_not_net);
                retryText.setText("网络异常，点击屏幕重新加载");
                root_content_null_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        root_content_null_ll.setVisibility(View.GONE);
                        refreshLayout.setVisibility(View.VISIBLE);
                        pn = 1;
                        getfolowgames();
                    }
                });

//                topLayout.setVisibility(View.VISIBLE);
//                showFailedLoding(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        topLayout.setVisibility(View.GONE);
//                        hideFailedLoding();
//                        getfolowgames();
//                    }
//                });
            }
        }
    }

    private String httptag = "";

    private void canclefolowgame(final String gameId) {
        api.getCancleFollowGame(AccountUtil.getInstance().getUid(), gameId, AccountUtil.getInstance().getToken())
                .enqueue(new MyCallback<ResponseBase<ResponseSratues>>() {
                    @Override
                    public void onSuccess(ResponseBase<ResponseSratues> model) {
                        ResponseSratues data = model.getData_info();
                        if (data != null && data.isState()) {
                            Iterator<GameListBaseBean> iterator = games.iterator();
                            while (iterator.hasNext()) {
                                GameListBaseBean gameListBaseBean = iterator.next();
                                if (gameListBaseBean.getGame_id().equals(gameId)) {
                                    iterator.remove();
                                    adapter.notifyDataSetChanged();
                                    break;
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        showToast(msg);
                    }
                });
    }

    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    class MyupdateViewHolder extends RecyclerView.ViewHolder {

        ItemListView itemlistView;

        public MyupdateViewHolder(View itemView) {
            super(itemView);
            itemlistView = itemView.findViewById(R.id.itemView);
        }
    }

    class MYUpdateAdapter extends RecyclerView.Adapter {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = inflater.inflate(R.layout.gamelist_item_layout, parent, false);
            MyupdateViewHolder holder = new MyupdateViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
            MyupdateViewHolder h = (MyupdateViewHolder) holder;
            h.itemlistView.setData(MYFollowGamsActivity.this, games.get(position));
            h.itemlistView.hitLine();
            h.itemlistView.setOnclickLinstener(new ItemListView.ItemDownloadInterface() {
                @Override
                public void onAdapterItemLongChildClick(View view, DownLoadTaskTable taskTable) {
                    final MessageDialog messageDialog = new MessageDialog(context);
                    messageDialog.show();
                    messageDialog.setTitle(getResources().getString(R.string.comment_dialog_title_str));
                    messageDialog.setMsg("确定需要取消收藏吗?");
                    messageDialog.setCancelBtn(getResources().getString(R.string.comment_dialog_cancle_str), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            messageDialog.dismiss();
                        }
                    });
                    messageDialog.setOkBtn(getResources().getString(R.string.comment_dialog_ok_str), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            messageDialog.dismiss();
                            canclefolowgame(games.get(position).getGame_id());
                        }
                    });
                }


            });
        }

        @Override
        public int getItemCount() {
            return games.size();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        for (int i = 0; i < games.size(); i++) {
            final GameListBaseBean bean = games.get(i);
            if (bean.getGame_id().equals(downloadEvent.getGameId())) {
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }
                View view = recvcleView.getLayoutManager().findViewByPosition(i);
                ItemListView itemView = view.findViewById(R.id.itemView);
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);

            }

        }
        super.onEventMainThread(downloadEvent);
    }
}
